#include<iostream>
using namespace std;
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
/*全局变量*/
int g_ticket=10;
/*线程是共享全局变量的*/
/*线程函数*/
void *thread_func1(void *arg)
{
    /*线程分离*/
    pthread_detach(pthread_self());
    int val1=*(int *)arg;
    int cnt=100;
    while(g_ticket>0)
    {
        usleep(1000);
        g_ticket--;
         printf("i am new thread1.thread:%ld,val1=%d,g_ticket=%d\n",pthread_self(),val1,g_ticket);

    }
    /*线程退出*/
    pthread_exit(NULL);
}
void *thread_func2(void *arg)
{

    /*线程分离*/
    pthread_detach(pthread_self());
    int val2=*(int *)arg;
    int cnt=100;
    while(g_ticket>0)
    {   
        usleep(1500);
         g_ticket--;
         printf("i am new thread2.thread:%ld,val2=%d,g_ticket=%d\n",pthread_self(),val2,g_ticket);
       
    }
     /*线程退出*/
    pthread_exit(NULL);
}

void *thread_func3(void *arg)
{
    /*线程分离*/
    pthread_detach(pthread_self());
    int val3=*(int *)arg;
    int cnt=100;
    while(g_ticket>0)
    {
        usleep(1200);
        g_ticket--;
         printf("i am new thread3.thread:%ld,val3=%d,g_ticket=%d\n",pthread_self(),val3,g_ticket);
      
    }
     /*线程退出*/
    pthread_exit(NULL);
}

int main()
{  
    // /*进程号*/
    // pid_t pid=getpid();
    // /*线程号*/
    // pthread_t tid=pthread_self();
    // cout<<"pid:"<<pid<<endl;
    // cout<<"tid:"<<tid<<endl;
  

   /*创建线程*/
   pthread_t tid1;
   int val1=100;
   int ret= pthread_create(&tid1,NULL,thread_func1,&val1);
   if(ret!=0)
   {
      perror("thread create error");
      _exit(-1);
   }

    pthread_t tid2;
    int val2=200;
    ret= pthread_create(&tid2,NULL,thread_func2,&val2);
   if(ret!=0)
   {
      perror("thread create error");
      _exit(-1);
   }

    pthread_t tid3;
    int val3=200;
    ret= pthread_create(&tid3,NULL,thread_func3,&val3);
   if(ret!=0)
   {
      perror("thread create error");
      _exit(-1);
   }
//    /*阻塞回收线程资源*/
//    pthread_join(tid1,NULL);
//    pthread_join(tid2,NULL);


   printf("i am main thread...\n");


    int cnt=100;
    while(cnt--)
    {
        printf("i am main thread.\n");
        sleep(1);
    }
    return 0;
}